// ignore_for_file: depend_on_referenced_packages, deprecated_member_use

import 'dart:io';

import 'package:device_identity/device_identity.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:uuid/uuid.dart';
import 'package:xvideos/config/config.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/store_keys.dart';

import '../tools_base/debug_log.dart';
import 'light_model.dart';
import 'text_util.dart';

///获取设备id
Future<String> getDeviceOaid() async {
  String deviceStr = Config.deviceId;
  if (deviceStr.isEmpty) {
    try {
      await DeviceIdentity.register();
      var plugin = DeviceInfoPlugin();
      var androidInfo = await plugin.androidInfo;
      var sdkInt = androidInfo.version.sdkInt;

      if (sdkInt >= 29) {
        deviceStr = await DeviceIdentity.oaid;
        if (TextUtil.isEmpty(deviceStr) || isOnlyContainZero(deviceStr)) {
          deviceStr = await getDeviceId(plugin);
        }
      } else {
        deviceStr = await DeviceIdentity.imei;
        if (deviceStr.isEmpty) {
          deviceStr = await DeviceIdentity.oaid;
        }
        if (TextUtil.isEmpty(deviceStr) || isOnlyContainZero(deviceStr)) {
          deviceStr = await DeviceIdentity.androidId;
        }
        if (TextUtil.isEmpty(deviceStr) || isOnlyContainZero(deviceStr)) {
          deviceStr = await getDeviceId(plugin);
        }
      }
      if (TextUtil.isEmpty(deviceStr) || isOnlyContainZero(deviceStr)) {
        deviceStr = Uuid().v4();
      }
    } catch (e) {
      deviceStr = Uuid().v4();
    }
    deviceStr = 'xvideos_${deviceStr.replaceAll(' ', '')}';
    Config.deviceId = deviceStr;
  }
  return  deviceStr;
}

Future<String> getDeviceId(DeviceInfoPlugin plugin) async {
  var deviceStr = await lightKV.getString("device_id");
  if (TextUtil.isNotEmpty(deviceStr)) return deviceStr!;
  try {
    final androidInfo = await plugin.androidInfo;

    final androidid = await DeviceIdentity.androidId;

    if (TextUtil.isNotEmpty(androidid)) {
      deviceStr = "${androidInfo.brand}_$androidid";
    }
    if (TextUtil.isEmpty(deviceStr)) {
      deviceStr = Uuid().v4();
    }
  } catch (e) {
    deviceStr = Uuid().v4();
  }
  await lightKV.setString("device_id", deviceStr);
  return deviceStr!;
}

bool isOnlyContainZero(String input) {
  final regexp = RegExp(r'0');
  final matches = regexp.allMatches(input.replaceAll(' ', ''));
  return matches.length > 16;
}

///获取渠道
Future<String> getChannel() async {
  String? channel = "";
  if (Platform.isAndroid) {
    const platform = MethodChannel(Config.naticeChannel);
    try {
      channel = await platform.invokeMethod("getChannel");
    } on PlatformException {
      // channel = "1";
    }
  }
  return channel ?? "";
}

///浏览器跳转
Future launchUrlMethod(String url, {String? tip}) async {
  try {
    // if (await canLaunch(url)) {
    await launchUrl(Uri.parse(url), mode: LaunchMode.externalNonBrowserApplication);
    // } else {
    if (tip != null && tip.isNotEmpty) {
      showToast(tip);
    }
    // }
  } catch (e) {
    debugLog(e);
  }
}

///安装android和ios的app
installApp(String filePath) async {
  //判断权限是否已有
  if (await Permission.storage.request().isGranted) {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    deviceInfoPlugin.androidInfo.then((androidInfo) {
      InstallPlugin.installApk(filePath, appId: androidInfo.id);
    });
  }
}

Future<String> getDevType() async {
  String devType = "";
  try {
    DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      var androidInfo = await deviceInfoPlugin.androidInfo;
      devType = "${androidInfo.device}:${androidInfo.version.sdkInt}:id=${androidInfo.id}";
    } else if (Platform.isIOS) {
      var iosInfo = await deviceInfoPlugin.iosInfo;
      devType = "${iosInfo.systemName}:${iosInfo.systemVersion}";
    }
  } catch (e) {
    debugLog("devtype", "getDevType()...error:$e");
  }
  return devType;
}

/// 保存数据到相册
Future<bool> savePngDataToAblumn(Uint8List? pngBytes) async {
  if (pngBytes == null) return false;

  AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
  String androidVersion = androidInfo.version.release;

  PermissionStatus status;

  if (int.parse(androidVersion) <= 12) {
    status = await Permission.storage.request();

    if (!status.isGranted) {
      showToast("请检查权限是否开启");
      return false;
    }
  } else {
    status = await Permission.photos.request();

    if (!status.isGranted) {
      showToast("请检查权限是否开启");
      return false;
    }
  }

  var map = await ImageGallerySaver.saveImage(pngBytes);
  if (null != map && map["isSuccess"] == true) {
    showToast("保存成功");
    lightKV.setBool(StoreKeys.HAVE_SAVE_QR_CODE, true);
    return true;
  } else {
    showToast("保存失败，请手动截图");
    return false;
  }
}
